package com.edevp.common.security.web;

import com.edevp.common.core.dto.R;
import com.edevp.common.core.exception.EngineException;
import com.edevp.common.core.util.security.SecurityUtil;
import com.edevp.common.security.dto.AuthClientDTO;
import com.edevp.common.security.dto.AuthLoginUserParams;
import com.edevp.common.security.dto.AuthTokenDTO;
import com.edevp.common.security.dto.AuthUserDTO;
import com.edevp.common.security.exception.AuthExceptionCode;
import com.edevp.common.security.service.AuthClientDetailsService;
import com.edevp.common.security.service.AuthTokenService;
import com.edevp.common.security.service.AuthUserDetailsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.constraints.NotEmpty;

/**
 * @author lean
 * @date 2022-07-08 3:36 PM
 **/
@Controller
@RequestMapping("oauth")
@RequiredArgsConstructor
public class AuthTokenController {

	private final AuthClientDetailsService clientDetailsService;
	private final AuthUserDetailsService userDetailsService;
	private final AuthTokenService tokenService;

	/**
	* 密码模式获取token
	* @param loginParams 登录参数
	* @return R<AuthTokenDTO>
	* @author Blueeyedboy
	* @create 7/8/2022 3:43 PM
	**/
	@ResponseBody
	public R<AuthTokenDTO> getToken(@NotEmpty @RequestHeader("client_id") String clientId
			, @NotEmpty @RequestHeader("client_secret") String secret
			, @NotEmpty @RequestHeader("grant_type") String grantType
			, @RequestHeader("scope") String scope, @RequestBody @Validated AuthLoginUserParams loginParams){
		try {
			// 获取客户端
			AuthClientDTO clientDetails = clientDetailsService.load(clientId);
			if (clientDetails == null) {
				throw new EngineException(AuthExceptionCode.CLIENT_NOT_FIND);
			}
			// 比对密码
			if (!SecurityUtil.matchesPassword(secret, clientDetails.getClientSecret())) {
				throw new EngineException(AuthExceptionCode.CLIENT_SECRET_ILLEGAL);
			}
			// 获取用户
			AuthUserDTO userDetails = userDetailsService.load(loginParams);
			if (userDetails == null) {
				throw new EngineException(AuthExceptionCode.ERROR_USERNAME_PASSWORD);
			}
			// 创建token ， loginType可以从user-agent中获取
			AuthTokenDTO tokenDTO = tokenService.createToken(clientDetails,userDetails, loginParams.getLoginType());

			return R.ok(tokenDTO);
		}catch (EngineException e){
			int code = e.getCode();
			String msg = e.getMsg();
			throw e;
		}finally {
			// 记录登录日志到数据库
			log();
		}
	}

	private void log(){

	}
}
